const fs = require('fs')
const http = require('http')
http.createServer((request, response) => {
    // console.log('a request', getPrototypChain(request))
    // TODO 流
    // response.end('Hi Node')
    // 语义化
    // Best or nothing

    // response = 'hahaha'
    // response.body = 'heihei'

    const { url, method } = request
    if (url === '/' && method === 'GET') {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                response.writeHead(500, {
                    'Content-Type': 'text/plain;charset=utf-8'
                })
                response.end('500 服务器挂了')
                return
            }
            response.statusCode = 200
            response.setHeader('Content-type', 'text-html')
            response.end(data)
        })
    }
    else if (url === '/users' && method === 'GET') {
        response.writeHead(200, { 'Content-type': 'application/json' })
        response.end(JSON.stringify({ name: 'tom' }))
    }
    else if (method === 'GET' && url === headers.accept.indexOf('image/*')) {
        // 所有的图片
        // 直接用readFile读取，是否ok 把全部图片内容加载到服务器 （内存问题）
        // stream 流 url/1.png => ./1.png
        fs.createReadStream('.' + url).pipe(response)
    }
    else {
        response.statusCode = 404
        response.setHeader('Content-type', 'text/plain;charset=utf-8')
        response.end('404 没有这玩意')
    }

}).listen(3000, () => {
    console.log('Serve at 3000')
})

// function getPrototypChain(obj) {
//     const protoChain = []
//     while (obj = Object.getPrototypOf(obj)) {
//         protoChain.push(obj)
//     }
//     return
// }